Dictionaries are a very useful data structure. They are similar to lists, but instead of being indexed by integeres they are indexed by keys which can be of any type as long as they are immutable. In a dictionary the keys are used to access values.
A typical example would be the following:
In [ ]:
d = {'Angela': 23746, 'Sofia': 2514, 'Luis': 3747, 'Diego': 61562}
In this example the keys are strings (corresponding to names) and the values are numbers.
We can acess now the values:
In [ ]:
d['Angela']
In [ ]:
d['Diego']
In [ ]:
d['Luis']
In [ ]:
d['Sofia']
Adding a new element in the dictionary is very simple
In [ ]:
d['Valeriano'] = 1234
In [ ]:
print(d)
deleting an item is also easy to do
In [ ]:
d.pop('Angela')
In [ ]:
print(d)
It is possible to gather all the keys
In [ ]:
list(d.keys())
and also gather all the values
In [ ]:
list(d.values())
It is also easy to test whether a key (or value) is in the dictionary
In [ ]:
'Miguel' in d.keys()
In [ ]:
'Luis' in d.keys()
In [ ]:
In [ ]:
activities = {
'Monday': {'study':4, 'sleep':8, 'party':0},
'Tuesday': {'study':8, 'sleep':4, 'party':0},
'Wednesday': {'study':8, 'sleep':4, 'party':0},
'Thursday': {'study':4, 'sleep':4, 'party':4},
'Friday': {'study':1, 'sleep':4, 'party':8},
}
In [ ]: